<template>
	<el-form-item :label="title" :prop="prop">
		<el-cascader :value="inputValue" :props="props" :placeholder="placeholder" @change="onChange"></el-cascader>
	</el-form-item>
</template>

<script>
export default {
	name: 'Province',
	props: {
		value: {
			type: [String, Array],
			default: () => [],
		},
		title: {
			type: String,
			default: '',
		},
		prop: {
			type: String,
			default: '',
		},
		placeholder: {
			type: String,
			default: '',
		},
		//array or str
		type: {
			type: String,
			default: 'array',
		},
	},
	data() {
		return {
			props: {
				lazy: true,
				lazyLoad: (node, resolve) => {
					const { level } = node;
					const index = level === 0 ? 0 : 1;
					const apiUrl = {
						0: '/api/account/open/province',
						1: '/api/account/open/city_county',
					};
					this.$request
						.post(
							apiUrl[index],
							index === 1 && {
								id: node.value,
							}
						)
						.then((res) => {
							resolve(
								res.data.map((item) => ({
									value: item.objId,
									label: item.name,
									leaf: level >= 2,
								}))
							);
						});
				},
			},
		};
	},
	computed: {
		inputValue() {
			return this.renderValue(this.value);
		},
	},
	methods: {
		renderValue(val = []) {
			if (!val) return [];
			if (Array.isArray(val)) {
				return val;
			}
			return val.split(',').map((n) => +n);
		},
		onChange(data) {
			this.$emit('input', this.type === 'array' ? data : data.join(','));
		},
	},
};
</script>

<style scoped lang="scss"></style>
